package com.zqweb.gulimall.gateway.config;


import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.fastjson.JSON;
import com.zqweb.common.exception.ExpCodeAndMsgEnum;
import com.zqweb.common.utils.R;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Configuration
public class GatewaySentinelConfig {
    // 自定义网关处Sentinel的流控响应结果
    // TODO 响应式编程（天然支持高并发）
    public GatewaySentinelConfig(){
        GatewayCallbackManager.setBlockHandler(new BlockRequestHandler() {
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) {
                R err = R.error(ExpCodeAndMsgEnum.REQ_TOOMANY_EXCEPTION.getCode(), ExpCodeAndMsgEnum.REQ_TOOMANY_EXCEPTION.getMsg() + ":GateWay!");
                String errJSON = JSON.toJSONString(err);
                Mono<ServerResponse> errMono = ServerResponse.ok().body(Mono.just(errJSON), String.class);
                return errMono;
            }
        });

    }

}
